package cn.net.cfss.fgbp.gateway.config;

import cn.net.cfss.fgbp.base.common.GlobalConstants;
import cn.net.cfss.fgbp.base.except.CodeException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class GlobalErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {

        if (getError(request) instanceof CodeException) {
            Map<String, Object> map=new HashMap<>();
            CodeException ex = (CodeException) getError(request);
            map.put(GlobalConstants.PARAMS_RETURN_CODE, ex.getCode());
            map.put(GlobalConstants.PARAMS_RETURN_MSG, ex.getErrMsg());
            map.put("status", "200");
            log.error("err:url={},err={}",request.exchange().getRequest().getURI().getPath(), JSONObject.toJSONString(map));
            return map;
        }
        Map<String, Object> map = super.getErrorAttributes(request, includeStackTrace);
        log.error("err:url={},err={}",request.exchange().getRequest().getURI().getPath(),JSONObject.toJSONString(map));
        return map;
    }
}
